package sqlsession;

import config.Configuration;
import config.MappedStatement;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * @CreatedBy richInfo AI
 * @ClassName DefaultSqlSession
 * @Date 2021/8/16 2:23 下午
 * @Author xin.yang
 * @Description TODO
 */
public class DefaultSqlSession implements SqlSession
{

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration)
    {
        this.configuration = configuration;
    }


    @Override
    public <U> List<U> selectList(String id, Configuration configuration, Object... args) throws Exception
    {
        Executor sampleExecutor = new SampleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(id);
        return sampleExecutor.selectList(mappedStatement, configuration, args);
    }


    @Override
    public int save(String id, Configuration configuration, Object... args) throws Exception
    {
        SampleExecutor sampleExecutor = new SampleExecutor();
        return sampleExecutor.save(configuration.getMappedStatementMap().get(id), configuration, args);
    }

    @Override
    public <U> U getMapper(Class<?> cls)
    {
        return (U) Proxy.newProxyInstance(cls.getClassLoader(), new Class[]{cls}, new InvocationHandler()
        {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
            {
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                if (methodName.equals("save"))
                {
                    return save(className + "." + methodName, configuration, args);
                }
                else
                {
                    return selectList(className + "." + methodName, configuration, args);
                }
            }
        });
    }
}
